<?php

namespace App\Http\Controllers\hotel;

use App\Models\Business\Business as BusinessModel;
use App\Models\Business\Record as RecordModel;
use App\Models\Config as ConfigModel;

use Illuminate\Http\Request;
// 引入Validator 门面 
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;


class Business extends Controller
{

    // 登陆
    public function login()
    {
        $mobile = request('mobile', '');
        $password = request('password', '');

        $userinfo = BusinessModel::where('mobile', $mobile)->first();

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        $password = md5($password . $userinfo['salt']);

        if ($password != $userinfo['password']) {
            return  error('密码或用户名错误请重新输入');
        }

        $url = ConfigModel::where('name', 'url')->value('value');

        $avatar = HttpRequest($url . '/base/business/avatar', ['busid' => $userinfo['id']]);

        $data = [
            'id' => $userinfo['id'],
            'mobile' => $userinfo['mobile'],
            'nickname' => $userinfo['nickname'],
            'avatar' => $avatar,
            'gender' => $userinfo['gender'],
            'province' => $userinfo['province'],
            'city' => $userinfo['city'],
            'district' => $userinfo['district'],
            'createtime' => date("Y-m-d H:i:s", strtotime($userinfo['createtime'])),
            'money' => $userinfo['money'],
            'email' => $userinfo['email'],
            'region' => $userinfo['region'],
            'auth' => $userinfo['auth']
        ];

        return success('登陆成功', $data);
    }

    // 注册
    public function register()
    {
        $mobile = request('mobile', '');
        $password = request('password', '');

        // 获取密码盐
        $salt = build_ranstr();

        $data = [
            'mobile' => $mobile,
            'password' =>  md5($password . $salt),
            'salt' => $salt,
            'nickname' => $mobile
        ];

        // 验证规则
        $rules = [
            'mobile' => 'required|unique:business',
            'password' => 'required',
            'salt' => 'required'
        ];

        // 错误提示信息
        $message = [
            'mobile.required' => '手机号码必须填写',
            'mobile.unique' => '手机号码已注册，请重新输入',
            'password.required'   => '密码必须填写',
            'salt.required'  => '密码盐必须填写',
        ];

        // make 方法将会生成一个新的验证器实例
        $validator = Validator::make($data, $rules, $message);

        if ($validator->fails()) {
            // errors 获取所有错误信息
            $errors = $validator->errors();
            // first 第一个错误信息;
            return error($errors->first());
        }

        // 用户表验证器校验数据并且添加
        $result = BusinessModel::create($data);

        if ($result === FALSE) {
            return  error('注册失败');
        } else {
            return success('注册成功');
        }
    }

    // 校验
    public function check()
    {
        $id = request('id', '');
        $mobile = request('mobile', '');

        $userinfo = BusinessModel::where(['id' => $id, 'mobile' => $mobile])->first();

        if (!$userinfo) {
            return  error('当前用户不存在');
        }

        $url = ConfigModel::where('name', 'url')->value('value');

        $avatar = HttpRequest($url . '/base/business/avatar', ['busid' => $userinfo['id']]);

        $data = [
            'id' => $userinfo['id'],
            'mobile' => $userinfo['mobile'],
            'nickname' => $userinfo['nickname'],
            'avatar' => $avatar,
            'gender' => $userinfo['gender'],
            'province' => $userinfo['province'],
            'city' => $userinfo['city'],
            'district' => $userinfo['district'],
            'createtime' => date("Y-m-d H:i:s", strtotime($userinfo['createtime'])),
            'money' => $userinfo['money'],
            'email' => $userinfo['email'],
            'region' => $userinfo['region'],
            'auth' => $userinfo['auth']
        ];

        return success('校验成功', $data);
    }

    // 修改个人资料
    public function profile(Request $request)
    {
        $id = request('id', 0);

        $password = request('password', '');

        $params = $request->all();

        $userinfo = BusinessModel::find($id);

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        $data = [
            'nickname' => $params['nickname'],
            'email' => $params['email'],
            'gender' => $params['gender'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district'],
        ];


        // 修改密码
        if (!empty($password)) {
            $password = md5($password . $userinfo['salt']);
            if ($password == $userinfo['password']) {
                return error('修改的密码与原密码一致');
            }
            $data['password'] = $password;
        }

        $url = ConfigModel::where('name', 'url')->value('value');

        // 修改头像
        if (isset($_FILES['avatar']) &&  $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
            // 第一个参数是上传成功的临时文件 第二个参数是文件类型 第三个是文件名
            $file = new \CURLFile($_FILES['avatar']['tmp_name'], $_FILES['avatar']['type'], $_FILES['avatar']['name']);

            $res = HttpRequest($url . '/base/business/upload', [
                'busid' => $userinfo['id'], 'avatar' => $file
            ]);

            $res = json_decode($res, true);

            if ($res['code'] == 0) {
                return error($res['msg']);
            }

            $data['avatar'] = $res['data'];
        }

        $result = BusinessModel::where(['id' => $id])->update($data);

        if ($result === FALSE) {
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                HttpRequest($url . '/base/business/del', [
                    'busid' => $userinfo['id'], 'avatar' => $data['avatar']
                ]);
            }

            return error('修改失败');
        } else {
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                HttpRequest($url . '/base/business/del', [
                    'busid' => $userinfo['id'], 'avatar' => $userinfo['avatar']
                ]);
            }
            $userinfo =  BusinessModel::find($id);

            $avatar = HttpRequest($url . '/base/business/avatar', ['id' => $userinfo['id']]);


            // 封装cookie数据
            $datas = [
                'id' => $userinfo['id'],
                'mobile' => $userinfo['mobile'],
                'nickname' => $userinfo['nickname'],
                'avatar' => $avatar,
                'gender' => $userinfo['gender'],
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'district' => $userinfo['district'],
                'createtime' => date("Y-m-d H:i:s", strtotime($userinfo['createtime'])),
                'money' => $userinfo['money'],
                'email' => $userinfo['email'],
                'region' => $userinfo['region'],
                'auth' => $userinfo['auth']
            ];

            return success('修改成功', $datas);
        }
    }

    // 获取消费记录
    public function record()
    {
        $busid = request('busid', 0);

        $userinfo =  BusinessModel::find($busid);

        if (!$userinfo) {
            return error('当前用户不存在');
        }

        $data = RecordModel::where(['busid' => $busid])->whereIn('state', ['2', '3'])->orderBy('createtime', 'desc')->get();

        return success('', '', $data);
    }
}
